<?php

namespace addons\csmitsm\library\xcore\xcflow\utils;

use think\Db;
use addons\csmitsm\library\sdnode\xstack\utils\XsDateUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcDatabaseUtils;

class XcformDataUtils
{

    /**
     * createMdmTable($xcformRow, "fa_xpframework_data_table001", "表格001");
     * @return void
     */
    public static function createOrUpdateTable($tablename, $tablecomment, $xcfieldjsonObj)
    {

        if (!XcDatabaseUtils::existsTable($tablename)) {
            $sql = "
              CREATE TABLE `{$tablename}` (
                 `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',             
                 `user_id` int(10) DEFAULT '0' COMMENT '会员ID',
                 `admin_id` int(10) DEFAULT '0' COMMENT '管理员ID',
                 `createtime` bigint(16) DEFAULT NULL COMMENT '创建时间',
                 `updatetime` bigint(16) DEFAULT NULL COMMENT '更新时间',
                 `weigh` int(10) DEFAULT '0' COMMENT '权重',
                 `status` enum('normal','hidden','draft') DEFAULT 'normal' COMMENT '状态:normal=正常,hidden=删除,draft=草稿',
                 PRIMARY KEY (`id`)
              ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='{$tablecomment}'
           ";
            Db::execute($sql);
        }

        // $xcfieldjsonObj = json_decode($xcform->xcfieldjson, true);
        if ($xcfieldjsonObj != null) {
            foreach ($xcfieldjsonObj as $field) {
                $fieldInstance = XcformFieldsUtils::createFieldInstance("xcform", $field);
                $fieldcode = $field['fieldcode'];
                $title = $field['title'];
                $columnType = $fieldInstance->getDbfieldColumnType();

                static::alertTableField("add_column", $tablename, $fieldcode, $columnType, $title);
            }
        }
    }

    public static function alertTableField($alterType, $tablename, $fieldcode, $columnType, $fieldcomment)
    {
        // if exists then add->change,if not exits change->add
        $alterType2 = $alterType;
        if ($alterType == 'add_column' && XcDatabaseUtils::existsTablefield($tablename, $fieldcode)) {
            $alterType2 = "change_column";
        } else if ($alterType == 'change_column' && !XcDatabaseUtils::existsTablefield($tablename, $fieldcode)) {
            $alterType2 = "add_column";
        }

        XcDatabaseUtils::alertTableField($alterType2, $tablename, $fieldcode, $columnType, $fieldcomment);
    }

    public static function getDbdataByXcformAndRowid($xcform, $rowid)
    {

        $tablename = $xcform->publishtablename;
        return XcDatabaseUtils::getRowById($tablename, $rowid);
    }

    // to test
    public static function getPagedatasByTablename($tablename, $xcfieldjsonObj, $wheres)
    {
        // $list = null;
        // if(true){
        //     $sql = Db::table($tablename);
        //     foreach($wheres as $where){
        //         $sql->where($where);
        //     }
        //     $list = $sql->select();
        // }
        $list = XcDatabaseUtils::getListBySql($tablename, $wheres);

        foreach($list as &$model){
            foreach ($xcfieldjsonObj as $field) {
                $fieldcode = $field['fieldcode'];
                if (!empty($fieldcode) && isset($model[$fieldcode])) {
                    $instance = XcformFieldsUtils::createFieldInstance("xcform", $field);
                    $model[$fieldcode] = $instance->dbvalueToPagevalue($model[$fieldcode]);
                }
            }
        }
        return $list;
    }

    public static function getPagedataByTablenameAndRowid($tablename, $xcfieldjsonObj, $rowId)
    {
        // $model =  Db::table($tablename)->where('id', $rowId)->find();
        $model = XcDatabaseUtils::getRowById($tablename, $rowId);
        foreach ($xcfieldjsonObj as $field) {
            $fieldcode = $field['fieldcode'];
            if (!empty($fieldcode) && isset($model[$fieldcode])) {
                $instance = XcformFieldsUtils::createFieldInstance("xcform", $field);
                $model[$fieldcode] = $instance->dbvalueToPagevalue($model[$fieldcode]);
            }
        }
        return $model;
    }
    private static function convertBlankToNull(&$rowData)
    {
        foreach ($rowData as $key => $value) {
            if (empty($value)) {
                $rowData[$key] = null;
            }
        }
    }
    public static function createData($tablename, $xcfieldjsonObj, $rowData)
    {
        if ($rowData == null) {
            return null;
        }
        static::convertBlankToNull($rowData);
        
        $row = null;
        if (true) {
            $model = [];
            if (isset($rowData['admin_id']) && XcDatabaseUtils::existsTablefield($tablename, 'admin_id')) {
                $model['admin_id'] = $rowData['admin_id'];
            }
            if (XcDatabaseUtils::existsTablefield($tablename, 'createtime')) {
                $model['createtime'] = time();
            }
            if (XcDatabaseUtils::existsTablefield($tablename, 'createdate')) {
                $model['createdate'] = XsDateUtils::getCurrentDatestring();
            }
            foreach ($xcfieldjsonObj as $field) {
                $fieldcode = $field['fieldcode'];
                if (isset($rowData[$fieldcode])) {
                    if (!in_array($field['fieldtag'], ["xcform_control_input_subtable"])) {
                        $instance = XcformFieldsUtils::createFieldInstance("xcform", $field);
                        $model[$fieldcode] = $instance->pagevalueToDbvalue($rowData[$fieldcode]);
                    }
                }
            }
            $row = XcDatabaseUtils::create($tablename, $model);
        }
        // save sub_table
        if (true) {
            foreach ($xcfieldjsonObj as $field) {
                $fieldcode = $field['fieldcode'];
                if (array_key_exists($fieldcode, $rowData)) {
                    if (isset($rowData[$fieldcode]) && in_array($field['fieldtag'], ["xcform_control_input_subtable"])) {
                        $instance = XcformFieldsUtils::createFieldInstance("xcform", $field);
                        $dbvalues = $instance->pagevalueToDbvalue($rowData[$fieldcode]);

                        foreach ($dbvalues as $dbvalue) {
                            $subtableForginfieldcode = $field['fieldjsonObj']['xcform_base_property_input_subtable']['subtableForginfieldcode'];
                            $targetTablename = $field['fieldjsonObj']['xcform_base_property_input_subtable']['tablename'];
                            $dbvalue[$subtableForginfieldcode] = $row['id'];
                            $dbvalue['status'] = 'normal';
                            XcDatabaseUtils::create($targetTablename, $dbvalue);
                        }
                    }
                }
            }
        }


        return static::getPagedataByTablenameAndRowid($tablename,  $xcfieldjsonObj, $row['id']);
    }

    public static function updateData($tablename, $xcfieldjsonObj, $rowId, $rowData)
    {
        if ($rowData == null) {
            return static::getPagedataByTablenameAndRowid($tablename, $xcfieldjsonObj, $rowId);
        }
        static::convertBlankToNull($rowData);
        // save main_table
        $row = null;
        if (true) {
            $model = [];
            if (XcDatabaseUtils::existsTablefield($tablename, 'updatetime')) {
                $model['updatetime'] = time();
            }
            if (XcDatabaseUtils::existsTablefield($tablename, 'updatedate')) {
                $model['updatedate'] = XsDateUtils::getCurrentDatestring();
            }
            foreach ($xcfieldjsonObj as $field) {
                $fieldcode = $field['fieldcode'];
                if (array_key_exists($fieldcode, $rowData)) {
                    if (!in_array($field['fieldtag'], ["xcform_control_input_subtable"])) {
                        $instance = XcformFieldsUtils::createFieldInstance("xcform", $field);
                        $model[$fieldcode] = $instance->pagevalueToDbvalue($rowData[$fieldcode]);
                    }
                }
            }
            $row = XcDatabaseUtils::save($tablename, $rowId, $model);
        }

        // save sub_table
        if (true) {
            foreach ($xcfieldjsonObj as $field) {
                $fieldcode = $field['fieldcode'];
                if (array_key_exists($fieldcode, $rowData)) {
                    if (isset($rowData[$fieldcode]) && in_array($field['fieldtag'], ["xcform_control_input_subtable"])) {
                        $instance = XcformFieldsUtils::createFieldInstance("xcform", $field);
                        $dbvalues = $instance->pagevalueToDbvalue($rowData[$fieldcode]);

                        $ids = [];
                        foreach ($dbvalues as $dbvalue) {
                            $subtableForginfieldcode = $field['fieldjsonObj']['xcform_base_property_input_subtable']['subtableForginfieldcode'];
                            $targetTablename = $field['fieldjsonObj']['xcform_base_property_input_subtable']['tablename'];
                            $dbvalue[$subtableForginfieldcode] = $row['id'];
                            $dbvalue['status'] = 'normal';
                            if (empty($dbvalue['id'])) {
                                $rr = XcDatabaseUtils::create($targetTablename, $dbvalue);
                                $ids[] = $rr['id'];
                            } else {
                                $rr = XcDatabaseUtils::save($targetTablename, $dbvalue['id'], $dbvalue);
                                $ids[] = $rr['id'];
                            }
                        }
                        XcDatabaseUtils::deleteRows($targetTablename, [
                            [$subtableForginfieldcode, "=", $row['id']],
                            ["id", "not in", $ids]
                        ]);
                    }
                }
            }
        }

        return static::getPagedataByTablenameAndRowid($tablename, $xcfieldjsonObj, $rowId);
    }

    public static function deleteData($tablename, $rowId)
    {
        Db::table($tablename)->where('id', $rowId)->update(['status' => 'hidden']);
    }
}
